//
//  ActivityMiaoshu.m
//  HappyStore
//
//  Created by 李小辉 on 16/6/15.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "ActivityMiaoshu.h"

@interface ActivityMiaoshu ()<UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,TZImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UITextView *dscTextView;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;//图片选择器
@property (strong, nonatomic) NSMutableArray *selectedImgAry;
@end

@implementation ActivityMiaoshu

- (NSMutableArray *)imageAry{
    if (!_imageAry) {
        _imageAry = [NSMutableArray array];
    }
    return _imageAry;
}
- (NSMutableArray *)showImgAry{
    if (!_showImgAry) {
        _showImgAry = [NSMutableArray array];
    }
    return _showImgAry;
}
- (NSMutableArray *)selectedImgAry{
    if (!_selectedImgAry) {
        _selectedImgAry = [NSMutableArray array];
    }
    return _selectedImgAry;
}

- (UIImagePickerController *)imagePickerVc{
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (iOS9Later) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
    }
    return _imagePickerVc;

}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"白色背景"] forBarMetrics:UIBarMetricsDefault];
    //找出导航栏的下边的黑线
    UIImageView *navBarHairlineImageView = [NaviBarLine findHairlineImageViewUnder:self.navigationController.navigationBar];
    navBarHairlineImageView.hidden = NO;
    navBarHairlineImageView.alpha = 0.5f;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    //找出导航栏的下边的黑线
    UIImageView *navBarHairlineImageView = [NaviBarLine findHairlineImageViewUnder:self.navigationController.navigationBar];
    navBarHairlineImageView.hidden = YES;

}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 190, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.text = @"活动介绍";
    titleLabel.textColor = RGB(45, 45, 45);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    
    // 设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"返回" highImage:@"返回"];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(btnClickRight)];
    rightBar.tintColor = RGB(45, 45, 45);
    self.navigationItem.rightBarButtonItem = rightBar;
    //选择图片
    UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(20, 350, 50, 50)];
    [button setImage:[UIImage imageNamed:@"re_project_add2"] forState:0];
    [button addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    self.addBtn = button;
    [self.view addSubview:self.addBtn];

    if (self.activityMiaoshuStr.length != 0 && ![self.activityMiaoshuStr isEqualToString:@"点击填写"]) {
        self.dscTextView.text = self.activityMiaoshuStr;
    }
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
}
#pragma mark - “加”按钮
- (void)btnClick{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"照片选择"
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"相机",@"相册", nil];
    
    actionSheet.tag = 200;
    [actionSheet showInView:self.view];

}
//显示image和添加按钮
- (void)showImageAndAddBtn{
    //先清除原来的imageView
    for (UIImageView *imageview in self.showImgAry) {
        [imageview removeFromSuperview];
    }

    for (int i=0; i<self.imageAry.count; i++) {
        if (i==self.imageAry.count-1) {
            self.addBtn.frame = CGRectMake(20 + i % 4 * ((screenW-20)/4) , 350 + i / 4 * 60 , 50, 50);
            [self.imageAry removeObject:self.addBtn];
            [self.view addSubview:self.addBtn];
        }else{
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20 + i % 4 * ((screenW-20)/4) , 350 + i / 4 * 60 , 50, 50)];
            NSLog(@"%f",imageView.frame.origin.x);
            imageView.image = self.imageAry[i];
            [self.showImgAry addObject:imageView];
            [self.view addSubview:imageView];
        }
        
    }
}

#pragma mark - 选择照片
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (actionSheet.tag) {
            
        case 200:
        {
            //先设定sourceType为相机，然后判断相机是否可用（ipod）没相机，不可用将sourceType设定为相片库
            UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
            pickerImage.delegate = self;
            pickerImage.allowsEditing = YES;//设置可编辑
            switch (buttonIndex) {
                case 0:
                {
                    NSLog(@"相机");
                    //                    pickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
                    //                    [self presentViewController:pickerImage animated:YES completion:nil];//进入照相界面
                    [self takePhoto];
                }
                    break;
                case 1:
                {
                    NSLog(@"相册");
                    //                    pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //图片库
                    //                    [self presentViewController:pickerImage animated:YES completion:nil];//进入照相界面
                    [self pushImagePickerController];
                }
                    break;
                case 2:
                {
                    NSLog(@"取消");
                }
                    break;
            }
        }
            break;
            
    }

}
#pragma mark - UIImagePickerController

- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) && iOS8Later) {
        // 无权限 做一个友好的提示
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else { // 调用相机
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            self.imagePickerVc.sourceType = sourceType;
            if(iOS8Later) {
                _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            }
            self.tabBarController.tabBar.hidden = YES;
            [self presentViewController:_imagePickerVc animated:YES completion:nil];
        } else {
            NSLog(@"模拟器中无法打开照相机,请在真机中使用");
        }
    }
}
#pragma mark UIImagePickerControllerDelegate
//该代理方法仅适用于只选取图片时
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo {
    NSLog(@"选择完毕----image:%@-----info:%@",image,editingInfo);
    //        //保存图片至相册
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    [self.imageAry addObject:image];
    [self.imageAry addObject:self.addBtn];
    [self showImageAndAddBtn];
}
//是否存入相处成功
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error) {
        [self showSingleIconBubble:@"保存失败"];
    } else {
        [self.selectedImgAry addObject:image];
    }
}

#pragma mark - TZImagePickerController

- (void)pushImagePickerController {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:6 delegate:self];
    
#pragma mark - 四类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = YES;
    
    // 1.如果你需要将拍照按钮放在外面，不要传这个参数
    imagePickerVc.selectedAssets = self.selectedImgAry; // optional, 可选的
    imagePickerVc.allowTakePicture = YES; // 在内部显示拍照按钮
    
    // 2. Set the appearance
    // 2. 在这里设置imagePickerVc的外观
    // imagePickerVc.navigationBar.barTintColor = [UIColor greenColor];
    // imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    // imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor];
    
    // 3. Set allow picking video & photo & originalPhoto or not
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate =YES;
#pragma mark - 到这里为止
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        self.imageAry = [NSMutableArray arrayWithArray:photos];
        self.selectedImgAry = [NSMutableArray arrayWithArray:assets];
        [self.imageAry addObject:self.addBtn];
        [self showImageAndAddBtn];
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

-(void)leftBarButtonItemClick{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"是否保存"
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                          [self.navigationController popViewControllerAnimated:YES];}];
    [defaultAction setValue:[UIColor redColor] forKey:@"titleTextColor"];
    UIAlertAction* defaultAction2 = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              [self btnClickRight];
                                                          }];
    [alert addAction:defaultAction];
    [alert addAction:defaultAction2];
    [self presentViewController:alert animated:YES completion:nil];
    
}
-(void)btnClickRight{
    NSMutableDictionary  *dic = [NSMutableDictionary dictionary];
    [dic setObject:self.dscTextView.text forKey:@"string"];
    [dic setObject:self.imageAry forKey:@"images"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"miaoshu" object:nil userInfo:dic];
    [self.navigationController popViewControllerAnimated:YES];
}

@end
